package com.http.filterlianxi;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(filterName = "myfilter", urlPatterns = "/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将ServletRequest转为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取session变量，并不重新创建新的session
        HttpSession session = request.getSession(false);
        // 获取请求uri
        String uri = request.getRequestURI();
        // 调用函数isPublic，判断当前请求是否为公共资源
        if (isPublic(uri)){
            filterChain.doFilter(request, response);
            return;
        }
        // 判断用户是否登录
        // 登录则继续，否则重定向到登录页面
        if (session.getAttribute("admin") != null){
            filterChain.doFilter(request, response);
        } else {
            response.sendRedirect("/pub/login.html");
        }
    }


    /**
     * 判断当前请求uri是否为公共资源
     * @param uri
     * @return
     */
    private boolean isPublic(String uri) {
        return uri.contains("/pub/") || uri.equals("/LoginServlet") || uri.equals("/RegisterServlet");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
